import { getToken, setToken, removeToken } from '@/utils/token'
import router, { resetRouter } from '@/router'
import { doPostQs, doGet, doPostJson } from '@/utils/utils'
import { hasOneOf } from '@/utils/tools'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  currentRole: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_CURRENT_ROLE: (state, currentRole) => {
    state.currentRole = currentRole
  }
}

const actions = {
  // user login
  login({ commit }, loginForm) {
    return new Promise((resolve, reject) => {
      doPostQs('/auth/login', loginForm, {}).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
        console.log(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      doGet('/user/user/one', {}).then(response => {
        const { data } = response
        if (!data) {
          reject('未获取到用户信息，请重新登录')
        }
        const roles = []
        doPostJson('/user-role/user/all-cond', {}, {}).then(response => {
          response.data.rows.forEach(userRole => {
            roles.push(userRole.roleTitle)
            if (userRole.isFirstRole) {
              commit('SET_CURRENT_ROLE', {
                id: userRole.roleId,
                title: userRole.roleTitle             
              })
            }
          })
          if (!roles || roles.length <= 0) {
            reject('未获取到用户角色')
          }
          const backendRoles = []
          doGet('/role/any/backend-roles', {}, {}, true).then(response => {
            response.data.rows.forEach(role => {
              backendRoles.push(role.title)
            })
            if (!hasOneOf(backendRoles, roles)) {
              reject('您的账号不可访问后台')
            }
            commit('SET_ROLES', roles)
            commit('SET_NAME', data.nickname)
            if (data.headicon) {
              commit('SET_AVATAR', data.headicon)
            } else {
              commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
            }
            resolve(roles)
          }).catch(error => { reject(error) })
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      doGet('/auth/logout', {}).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
